# -*- coding: utf-8 -*-
import datetime

from django.http import JsonResponse
from django.db.models import Avg, Max, Min, Count, Sum

from people.models import User
from task.models import Task, DataTask
# Create your views here.

def user_location(requst):
    context = {'worker': [], 'publisher':[]}
    worker_province = User.objects.annotate(Count('province'))
    for i in worker_province:
        context['worker'].append({'name':i.province, 'value': i.province__count})
    
    context['publisher'] = context['worker']
    return JsonResponse(context)
    
def user_age(request):
    current_year = int(datetime.datetime.now().strftime('%Y'))
    context = {'publisher-male':[], 'publisher-female':[],
               'worker-male':[], 'worker-female':[], 'x_axis':[]}
    for i in range(current_year-100, current_year, 5):
        context['x_axis'].append(str(i)+'~'+str(i+5))
        user_qs = User.objects.filter(birthday__range=(datetime.date(i,1,1), datetime.date(i+5,12,31)))
        context['publisher-male'].append(user_qs.filter(sex=1).count())
        context['publisher-female'].append(user_qs.filter(sex=2).count())
        context['worker-male'].append(user_qs.filter(sex=1).count())
        context['worker-female'].append(user_qs.filter(sex=2).count())

    return JsonResponse(context)
    
def money_exchange(request):
    time_now = datetime.datetime.now()
    start_date = time_now - datetime.timedelta(days=7)
    end_date = time_now
    dates = []
    for i in range((end_date-start_date).days):
        dates.append(start_date+datetime.timedelta(i))
    
    context = {'payment':[],'cash':[], 'x_axis':[], 'cost':[]}
    for i in dates:
        print '++++++++++++++++'
        print i.date
        result = Task.objects.filter(overtime__range=(i.date(), i.date()+datetime.timedelta(days=1))).aggregate(Sum('taskfare'), Sum('faretask'))
        context['x_axis'].append(i.strftime('%Y-%m-%d'))
        context['payment'].append(result['taskfare__sum'] or 0)
        context['cash'].append(result['faretask__sum'] or 0)
        context['cost'].append(0)
    return JsonResponse(context)